﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ClickGame.General
{
    public class Animation
    {
        private Texture2D _currentAnimation;
        private bool _isLoop;
        private float _frameSpeed;
        private int _currentFrame;
        private double _timePassed;
        private Rectangle _currentRec;

        public int FrameHeight
        {
            get { return _currentAnimation.Height; }
        }

        public int FrameWidth
        {
            get { return _currentAnimation.Height; }
        }

        public int MaxFrames
        {
            get { return _currentAnimation .Width/ FrameHeight; }
        }

        public Rectangle AnimationRectangle
        {
            get { return _currentRec; }
        }

        public Texture2D CurrentTexture
        {
            get { return _currentAnimation; }
        }

        public int CurrentFrame
        {
            get { return _currentFrame; }
        }

        public double TimePassed
        {
            get { return _timePassed; }
            set { _timePassed = value; }
        }

        public Animation(Texture2D texture, float frameSpeed, bool isLoop)
        {
            _currentAnimation = texture;
            _frameSpeed = frameSpeed;
            _isLoop = isLoop;
            _currentFrame = 0;
            TimePassed = 0;
            CalculateRect();
        }

        public void Update(GameTime gameTime)
        {
            TimePassed += gameTime.ElapsedGameTime.TotalSeconds;
            if (TimePassed >= _frameSpeed)
            {
                TimePassed = 0;
                CalculateRect();
            }
        }

        void CalculateRect()
        {
            Rectangle r = new Rectangle(FrameWidth*_currentFrame++, 0, FrameWidth, FrameHeight);
            if (_isLoop)
            {
                if (_currentFrame >= MaxFrames)
                {
                    _currentFrame = 0;
                }
            }
            else
            {
                if (_currentFrame >= MaxFrames)
                {
                    _currentFrame = MaxFrames-1;
                }
            }
            _currentRec = r;
        }

        public void ChangeTexture(Texture2D texture, float speed, bool isLoop)
        {
            _currentAnimation = texture;
            if(_currentFrame >= MaxFrames)
                _currentFrame = 0;
            TimePassed = 0;
            _frameSpeed = speed;
            _isLoop = isLoop;
            CalculateRect();
        }
    }
}
